<template>
    <div class="app-container">
        <div class="col-body" :style="{ height: HeightTable + 'px' }" v-loading="loading">
            <div class="tree-add" @click="onButton('add')">
                <el-button type="primary">新增</el-button>
            </div>
            <div class="mx-1" size="large">角色列表</div>
            <div class="blank"></div>
            <el-form ref="searchForm" inline :model="searchRules.form" :rules="searchRules.data">
                <el-form-item prop="blurry">
                    <el-input v-model="searchRules.form.blurry" placeholder="角色名称" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit('searchForm')">搜索</el-button>
                    <el-button @click="onReset('searchForm')">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tableData" stripe border style="width: 100%" :height="HeightTable - 170">
                <el-table-column property="id" label="序号" width="100" align="center" />
                <el-table-column property="name" label="角色名称" width="200" />
                <el-table-column property="description" label="描述" />
                <el-table-column label="状态" width="150" align="center">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isDelete" active-text="正常" inactive-text="停用" :active-value="0"
                            :inactive-value="1" inline-prompt @change="onButton('isDelete', scope)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="190">
                    <template #default="scope">
                        <el-button-group class="ml-4">
                            <el-button type="primary" size="mini" @click="onButton('power', scope)">权限</el-button>
                            <el-button type="primary" size="mini" @click="onButton('edit', scope)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="onButton('del', scope)">删除</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 10px;text-align: center;" background
                layout=" prev, pager, next, total, jumper" :total="tableTotal" :default-page-size="pageSize"
                :page-sizes="[15, 50, 100]" @current-change="onPageChange" />
        </div>
        <el-dialog :visible.sync="addWinShow" title="编辑角色" width="400px">
            <el-form ref="addForm" :model="addRules.form" :rules="addRules.data" label-width="90">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="addRules.form.name" placeholder="请输入组织名称" clearable />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="addRules.form.description" placeholder="请输入角色描述" clearable :rows="3"
                        type="textarea" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio v-model="addRules.form.isDelete" :label="0">正常</el-radio>
                    <el-radio v-model="addRules.form.isDelete" :label="1">停用</el-radio>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addWinShow = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit('addForm')">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog :visible.sync="treeWinShow" title="权限设置" width="400" draggable>
            <el-tabs class="tree-box">
                <el-tab-pane label="功能权限" name="0">
                    <el-tree ref="myTree0" style="width:100%;height:300px;overflow-y:auto" show-checkbox node-key="id"
                        default-expand-all lazy :load="onTreeLoad0" :props="{ isLeaf: 'leaf' }" />
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="treeWinShow = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit('addPower')">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { roles, lazy, menu, addRoles } from '@/api/jurisdiction';
export default {
    data() {
        return {
            loading: false,
            HeightTable: window.innerHeight - 90,
            activeId: 0,
            pageSize: 15,
            tableTotal: 0,
            tableData: [],
            searchRules: {
                form: {
                    blurry: ""
                },
                data: {}
            },
            addWinShow: false,
            addRules: {
                form: {},
                data: {
                    name: [{
                        required: true,
                        message: '请输入组织名称',
                        trigger: 'blur'
                    }]
                }
            },
            treeWinShow: false
        };
    },
    mounted() {
        this.getRoleList();
    },
    methods: {
        onTreeLoad0(node, resolve, reject) {
            setTimeout(() => {
                let idVal = null;
                if (node.data == undefined) {
                    idVal = 0
                } else {
                    idVal = node.data.id
                }
                this.getMenuLazy(idVal).then(res => {
                    return resolve(res);
                });
            }, 300);
        },
        onButton(type, li) {
            let form = {};
            if (li && typeof li.$index != undefined) {
                form = Object.assign({}, this.tableData[li.$index]);
            }
            switch (type) {
                case "add":
                    this.addWinShow = true;
                    this.addRules.form = {
                        name: "",
                        description: "",
                        isDelete: 0
                    };
                    break;
                case "edit":
                    this.addWinShow = true;
                    this.addRules.form = form;
                    break;
                case "isDelete":
                    this.loading = true
                    this.updateRole("put", form).then(res => {
                        this.$message({
                            message: '切换成功',
                            type: 'success',
                        });
                        this.loading = false
                    }).catch(error => {
                        this.tableData[li.$index][type] = li.row[type] == 0 ? 1 : 0;
                        this.loading = false
                    });
                    break;
                case "power":
                    this.treeWinShow = true;
                    this.activeId = form.id;
                    let ckids = [];
                    if (form.menus && form.menus.length > 0) {
                        ckids = form.menus.map(item => item.id);
                    }
                    setTimeout(() => {
                        this.$refs.myTree0.setCheckedKeys(ckids);
                    }, 100);
                    break;
                case "del":
                    this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.updateRole("delete", [form.id]).then(res => {
                            this.$message({
                                message: '删除成功',
                                type: 'success',
                            });
                            this.getRoleList(1);
                        });
                    }).catch(() => {
                    });


                    break;
            }
        },
        onReset(refname) {
            this.$refs[refname].resetFields();
            this.getRoleList(1);
        },
        onSubmit(refname) {
            let form = {};
            switch (refname) {
                case "addPower":
                    let menus = this.$refs.myTree0.getCheckedNodes();
                    menus = menus.map(item => {
                        return {
                            id: item.id
                        };
                    });
                    form = {
                        id: this.activeId,
                        menus: menus
                    };
                    this.updateMenus(form).then(res => {
                        this.$message({
                            message: '保存成功',
                            type: 'success',
                        });
                        this.treeWinShow = false;
                        this.getRoleList(1);
                    });
                    break;
                default:
                    this.$refs[refname].validate(valid => {
                        if (valid) {
                            switch (refname) {
                                case "searchForm":
                                    form = this.searchRules.form;
                                    let search = ``;
                                    for (const name in form) {
                                        if (form[name] !== "") {
                                            search += `&${name}=${form[name]}`;
                                        }
                                    }
                                    this.getRoleList(1, search);
                                    break;
                                case "addForm":
                                    form = Object.assign({
                                        dataScope: "全部",
                                        depts: [],
                                        level: 2,
                                    }, this.addRules.form);
                                    this.updateRole(form.id ? 'put' : 'post', form).then(res => {
                                        this.$message({
                                            message: '保存成功',
                                            type: 'success',
                                        });
                                        this.addWinShow = false;
                                        this.getRoleList(1);
                                    });
                                    break;
                            }
                        }
                    });
                    break;
            }
        },
        onPageChange(page) {
            this.getRoleList(page);
        },
        async getRoleList(page, search) {
            page = page ? page : 1;
            search = search ? search : "";
            this.loading = true
            roles(this.pageSize, page, search).then((res) => {
                this.tableData = res.data.content;
                this.tableTotal = res.data.totalElements;
                this.loading = false
            }).catch((err) => {
                this.loading = false
            })
        },
        //修改角色信息
        async updateRole(type, form) {
            let result = await addRoles(type, form)
            return Promise.resolve(result.data);
        },
        //修改角色菜单
        async updateMenus(form) {
            let result = await menu(form)
            return Promise.resolve(result.data).catch();
        },
        async getMenuLazy(pid) {
            pid = pid ? pid : 0;
            let result = await lazy(pid)
            return Promise.resolve(result.data);
        }
    }
};
</script>

<style lang="scss" scoped>
.col-body .el-input {
    --el-input-width: 220px;
}

.col-body .el-select {
    --el-select-width: 220px;
}

.blank {
    height: 20px;
}

.blank.line {
    height: auto;
    padding-top: 10px;
    margin-bottom: 10px;
    border-bottom: 1px #EBEEF5 solid;
}

.col-body {
    position: relative;
    padding: 20px;
    background: #FFFFFF;
}

.tree-add {
    position: absolute;
    right: 20px;
}
</style>